<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="550px"
        :clickModalClose="true"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
        <el-form-item label="所属站点" prop="siteId">
          <el-select v-model="formData.siteName" placeholder="请选择所属站点" @change="select(formData.siteName)" >
            <el-option 
                v-for="site in dictData.sites.lists"
                :key="site.id"
                :label="site.siteName"
                :value="site.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="formData.deviceName" placeholder="请输入设备名称"/>
        </el-form-item>
        <el-form-item label="订阅主题" prop="topic">
          <el-input v-model="formData.topic" placeholder="请输入mqtt订阅"/>
        </el-form-item>
		<el-form-item label="ClientID" prop="clientId">
		  <el-input v-model="formData.clientId" placeholder="请输入ClientID"/>
		</el-form-item>
		<el-form-item label="设备IMEI" prop="address">
		  <el-input v-model="formData.address" placeholder="请输入设备的IMEI"/>
		</el-form-item>
		<el-form-item label="操作密码" prop="devicePassword">
		  <el-input v-model="formData.devicePassword" type="password" placeholder="请输入设备操作密码"/>
		</el-form-item>
		<el-form-item label="设备类型" prop="deviceType">
		  <el-select v-model="formData.deviceType" placeholder="请选择站点类型">
		    <el-option 
		        v-for="type in deviceTypeOptions"
		        :key="type.value"
		        :label="type.label"
		        :value="type.value"
		    ></el-option>
		  </el-select>
		</el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type {FormInstance} from 'element-plus'
import {deviceAdd, fetchSiteList,detail,deviceEdit} from '@/api/devicebysite'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type {PropType} from 'vue'

defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑设备' : '新增设备'
})

const formData = reactive({
  id: '',
  siteId: '',
  siteName:'',
  deviceName: '',
  deviceState: '',
  deviceManageId: '',
  remoteState: '',
  peakElectricity: '',
  ebbElectricity: '',
  liquId: '',
  mudState: '',
  sewageState: '',
  devicePassword: '',
  topic:'',
  address:'',
  clientId: '',
  deviceType: '',
})

const deviceTypeOptions = [
  {label: '通用版', value: 1},
  {label: '2台潜污泵版', value: 2}
];
// //存放站点数据
const dictData = reactive({
  sites: []  // 存储站点名称数据
});
// //设置站点数据
onMounted(async () => {
  dictData.sites = await fetchSiteList(); // 调用后端接口获取站点数据，并赋值给dictData.sites
});

const formRules = {
  siteId: [
    {
      required: true,
      message: '请选择所属站点',
      trigger: ['blur']
    }
  ],
  deviceName: [
    {
      required: true,
      message: '请输入设备名称',
      trigger: ['blur']
    }
  ],
  devicePassword: [
    {
      required: true,
      message: '请输入站点参数操作密码',
      trigger: ['blur']
    }
  ],
  topic: [
    {
      required: true,
      message: '请输入mqtt订阅',
      trigger: ['blur']
    }
  ],
  address: [
	  {
		  required: true,
		  message: '请输入设备的IMEI',
		  trigger: ['blur']
	  }
  ],
  deviceType: [
  	  {
  		  required: true,
  		  message: '请选择站点类型',
  		  trigger: ['blur']
  	  }
  ]
}


const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

const select =(data: any)=>{
	formData.siteId=formData.siteName
}

const getDetail = async (row: Record<string, any>) => {
	formData.id=row.id
  const data = await detail({
    id: formData.id
  })
  setFormData(data)
}

const setFormData = async (data: Record<string, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
}

const handleClose = () => {
  formData.address ='',
  formData.deviceName ='',
  formData.topic ='',
  formData.siteId ='',
  formData.devicePassword='',
  formData.clientId=''
  emit('close')
}

defineExpose({
  open,
  setFormData,
  getDetail
})

const handleSubmit = async () => {
  await formRef.value?.validate()
  const data: any = {...formData}
  
  if(mode.value == 'edit'){ 
	  await deviceEdit(data)
  }else{
	  await deviceAdd(data)
  }   
  popupRef.value?.close()
  feedback.msgSuccess('操作成功')
  emit('success')
}
</script>
